package com.gw2.gw2world.controller;

import java.io.Serializable;

import com.gw2.gw2world.R;
import com.gw2.gw2world.model.Language;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;

public class LanguageAdapter extends ArrayAdapter<Language> implements OnCheckedChangeListener, Serializable {
	private static final long serialVersionUID = 1L;
	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	public LanguageAdapter(Context context, Language[] l) {
		super(context, android.R.layout.simple_list_item_1, l);
		setDropDownViewResource(R.layout.language);
		prefs=PreferenceManager.getDefaultSharedPreferences(getContext());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.language, parent, false);
		}
		RadioButton rb = (RadioButton) convertView.findViewById(R.id.rb_language);
		rb.setText(getItem(position).name);
		String flag = getContext().getResources().getStringArray(R.array.code)[position];
		rb.setCompoundDrawables(null,null, getContext().getResources().getDrawable(
				getContext().getResources().getIdentifier(flag, "drawable",getContext().getPackageName())),null);
		rb.setTag(getItem(position));
		rb.setOnCheckedChangeListener(this);
		return convertView;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		Language l=(Language)buttonView.getTag();
		if(isChecked) {
			editor=prefs.edit();
			editor.putString("language", l.code);
			editor.commit();
		}
	}

}
